package com.ziq.zcamp.dialog

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.CommentItem
import com.ziq.zcamp.bean.post.ReplyCommentItem
import com.ziq.zcamp.databinding.DialogAllCommentListBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.mine.PersonalHomePageActivity
import com.ziq.zcamp.post.AllCommentAdapter
import com.ziq.zcamp.post.CommentViewModel

class AllCommentListDialog(val activity: AppCompatActivity, val create_uid: Int, val post_id:String, val source: String) : BaseDialog(activity) {

    private val dialogbinding: DialogAllCommentListBinding by binding()
    lateinit var allCommentAdapter: AllCommentAdapter

    val mViewModel: CommentViewModel by activity.viewModels()

    override fun initHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }
    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.decorView?.systemUiVisibility =
                window?.decorView?.systemUiVisibility!! or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        }

        dialogbinding.root
        dialogbinding.root.click {
            dismiss()
        }
        val lp = dialogbinding.refreshLayout.layoutParams as ConstraintLayout.LayoutParams
        lp.height = ScreenUtils.getScreenHeight() / 10 * 5
        dialogbinding.refreshLayout.layoutParams = lp
        dialogbinding.refreshLayout.setOnRefreshListener {
            mViewModel.onRefreshComment()
        }
        dialogbinding.refreshLayout.setOnLoadMoreListener {
            mViewModel.onLoadMoreComment()
        }


        allCommentAdapter = AllCommentAdapter(context, mViewModel, source)
        allCommentAdapter.setActionListener(object : AllCommentAdapter.ActionListener {
            override fun onCommentUserInfoClick(item: CommentItem) {
                if(!activity.isFinishing){
                    PersonalHomePageActivity.open(activity, item.user_info?.uid?:0)
                }
            }

            override fun onReplyCommentUserInfoClick(item: ReplyCommentItem) {
                if(!activity.isFinishing){
                    PersonalHomePageActivity.open(activity, item.reply_info?.uid?:0)
                }
            }

            override fun onCommentItemClick(
                item: CommentItem,
                groupPosition: Int,
                adapterPosition: Int
            ) {
                if(!activity.isFinishing){
                    smoothMoveToPosition(dialogbinding.rvAllCommentList, adapterPosition)
                    CommentInputDialog(activity, mViewModel.postId, mViewModel.create_uid,
                        position = groupPosition, commentItem = item, source = source).show()
                }
            }

            override fun onReplyCommentItemClick(item: ReplyCommentItem, groupPosition: Int, adapterPosition:Int) {
                if(!activity.isFinishing){
                    smoothMoveToPosition(dialogbinding.rvAllCommentList, adapterPosition)
                    CommentInputDialog(activity, mViewModel.postId, mViewModel.create_uid,
                        position = groupPosition, replyCommentItem = item, source = source).show()
                }
            }
        })


        dialogbinding.rvAllCommentList.layoutManager = LinearLayoutManager(context)
        dialogbinding.rvAllCommentList.adapter = allCommentAdapter
        mViewModel.commentListScrollToPosition.observe(this, Observer<Int> {
            smoothMoveToPosition(dialogbinding.rvAllCommentList, it)
        })
        mViewModel.commentListRequestFinished.observe(this, Observer<Boolean> {
            if(it == true){
                dialogbinding.refreshLayout.finishRefresh()
                dialogbinding.refreshLayout.finishLoadMore()
            }
        })
        mViewModel.commentListHasMore.observe(this, Observer<Boolean> {
            if(it == true){
                dialogbinding.refreshLayout.resetNoMoreData()
            } else {
                dialogbinding.refreshLayout.setNoMoreData(true)
            }
        })
        mViewModel.commentData.observe(this, Observer {
            updateComment(it)
        })

        mViewModel.currentInput.observe(this, Observer {
            dialogbinding.commentAction.tvCommentActionInput.text = it
        })
        mViewModel.commentCount.observe(this, Observer { count ->
            updateUI(mViewModel.commentCount.value?:0, mViewModel.likeStatus.value?.num?:0, mViewModel.likeStatus.value?.isLike?:false, false)
        })

        mViewModel.likeStatus.observe(this, Observer { count ->
            updateUI(mViewModel.commentCount.value?:0, mViewModel.likeStatus.value?.num?:0, mViewModel.likeStatus.value?.isLike?:false, false)
        })

        updateUI(mViewModel.commentCount.value?:0, mViewModel.likeStatus.value?.num?:0, mViewModel.likeStatus.value?.isLike?:false, true)

        mViewModel.allCommentListDialogStatusShow.observe(this, Observer {
            it?.let { data ->
                dialogbinding.statusView.setStatus(it.status, updateActionBtn = { btn ->
                    btn.click {
                        data.action
                    }
                })
            }
        })

        dialogbinding.root.post {
            window!!.navigationBarColor = Color.BLACK
        }

        setAnimateView(dialogbinding.clCommentList)
    }

    override fun dismiss() {
        super.dismiss()
    }

    private fun updateUI(commentCount: Int, likeCount: Int, isLike:Boolean, considerManager: Boolean) {
        //评论
        dialogbinding.tvTitle.text = GlobalContextManager.getString(R.string.all_comment, commentCount)

        dialogbinding.commentAction.llCommentActionPraise.click {
            LoginActivity.checkLogin( object : ActionAfterLogin {
                override fun action() {
                    //点赞 帖子
                    if(dialogbinding.commentAction.llCommentActionPraise.isSelected){
                        updateDataForUnLike()
                        UserManager.instance.unlikePosting(mViewModel.postId, mViewModel.create_uid, likeCount, onFail = {
                            updateDataForLike()
                        })
                        startPraiseSvga("like_cancel.svga")
                    } else {
                        updateDataForLike()
                        UserManager.instance.likePosting(mViewModel.postId, mViewModel.create_uid, likeCount, onFail = {
                            updateDataForUnLike()
                        })
                        startPraiseSvga("like_commit.svga")
                    }
                }
            })
        }
        dialogbinding.commentAction.llCommentActionAllComment.click {
            dismiss()
        }

        dialogbinding.commentAction.tvCommentActionInput.click {
            LoginActivity.checkLogin( object : ActionAfterLogin {
                override fun action() {
                    if(activity.isFinishing){
                        return
                    }
                    CommentInputDialog(activity, mViewModel.postId, mViewModel.create_uid, source = source).show()
                }
            })
        }

        updateCommentUI(commentCount)
        updateLikeUI(considerManager, likeCount, isLike)
    }

    fun updateDataForLike(){
        mViewModel.likeStatus.value?.let {
            mViewModel.likeStatus.value = UserManager.PostingLikeStatus(it.num + 1, true)
        }
    }

    fun updateDataForUnLike(){
        mViewModel.likeStatus.value?.let {
            if(it.num > 0){
                mViewModel.likeStatus.value = UserManager.PostingLikeStatus(it.num - 1, false)
            }
        }
    }

    fun updateLikeUI(considerManager: Boolean, likeCount: Int, isLike:Boolean){
        var tempLikeCount = likeCount
        if(considerManager && UserManager.instance.postingLike.value?.contains(mViewModel.postId) == true){
            dialogbinding.commentAction.llCommentActionPraise.isSelected = UserManager.instance.postingLike.value!![mViewModel.postId]!!.isLike
            tempLikeCount = UserManager.instance.postingLike.value!![mViewModel.postId]!!.num
            if(tempLikeCount > 0){
                dialogbinding.commentAction.tvCommentActionPraiseCount.text = "$tempLikeCount"
            } else {
                dialogbinding.commentAction.tvCommentActionPraiseCount.text = GlobalContextManager.getString(R.string.give_a_like)
            }
        }else {
            dialogbinding.commentAction.llCommentActionPraise.isSelected = isLike
            if(tempLikeCount > 0){
                dialogbinding.commentAction.tvCommentActionPraiseCount.text = "$tempLikeCount"
            } else {
                dialogbinding.commentAction.tvCommentActionPraiseCount.text = GlobalContextManager.getString(R.string.give_a_like)
            }
        }

        if(!dialogbinding.commentAction.ivCommentActionPraise.isAnimating){
            dialogbinding.commentAction.ivCommentActionPraise.clearsAfterStop = false
            dialogbinding.commentAction.ivCommentActionPraise.loops = 1
            if(dialogbinding.commentAction.llCommentActionPraise.isSelected){
            } else {
            }
        }
    }

    fun updateCommentUI(commentCount: Int){
        if(commentCount > 0){
            dialogbinding.commentAction.tvCommentActionAllCommentCount.text = "$commentCount"
        }else {
            dialogbinding.commentAction.tvCommentActionAllCommentCount.text = GlobalContextManager.getString(R.string.comment)
        }
    }

    fun startPraiseSvga(path:String){
        dialogbinding.commentAction.ivCommentActionPraise.clearsAfterStop = false
        dialogbinding.commentAction.ivCommentActionPraise.loops = 1
    }



    fun updateComment(comments :MutableList<CommentItem>?) {
        allCommentAdapter.setData(comments)
    }

    /** 目标项是否在最后一个可见项之后 */
    private var mShouldScroll = false

    /** 记录目标项位置 */
    private var mToPosition = 0
    /**
     * 滑动到指定位置
     */
    private fun smoothMoveToPosition(mRecyclerView:RecyclerView , position:Int) {
        // 第一个可见位置
        val firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        val lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1))
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前，使用smoothScrollToPosition
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后，最后一个可见项之前
            val movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                val top = mRecyclerView.getChildAt(movePosition).getTop();
                // smoothScrollToPosition 不会有效果，此时调用smoothScrollBy来滑动到指定位置
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
//            mToPosition = position;
//            mShouldScroll = true;
        }
    }

}